package com.example.satoken.config.satokenconfig;

import com.example.satoken.config.saInterceptor.CustomInterceptor;
import com.example.satoken.config.saInterceptor.SaTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class SaTokenWebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private SaTokenUrlConfig saTokenUrlConfig;

    //放行路径
    private static final String[] EXCLUDE_PATH_PATTERNS = {
            // Swagger
            "**/swagger-ui.html",
            "/swagger-resources/**",
            "/webjars/**",
            "/v2/**",
            "/swagger-ui.html/**",
            "/doc.html/**",
            "/error",
            "/favicon.ico",
            "sso/auth",
            "/druid/**",
            "/actuator",
            "/actuator/**"
    };

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        /**
         * 放行路径 , 获取配置文件中的白名单路径: excludePath
         */
        List<String> excludePath = new ArrayList<>(Arrays.asList(EXCLUDE_PATH_PATTERNS));
        excludePath.addAll(saTokenUrlConfig.getOpenUrlList());


        /**
         *  注册 SaTokenInterceptor 拦截器 登录拦截器
         */

        registry.addInterceptor(new SaTokenInterceptor())
                .addPathPatterns(saTokenUrlConfig.getInterceptUrlList())
                .excludePathPatterns(excludePath).order(1);

        /**
         * sa-token中的token续签的拦截器,15min内有请求就token续期，不操作就过期。
         */
        registry.addInterceptor(new CustomInterceptor())
                .addPathPatterns(saTokenUrlConfig.getInterceptUrlList())
                .excludePathPatterns(excludePath).order(2);
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600)
                .exposedHeaders();
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOrigin("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

    /**
     * 解决静态资源无法访问 ,针对swagger-ui
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
